<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>订单导出接口测试 (端口82)</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            margin: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        .section {
            margin-bottom: 40px;
            padding: 20px;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
        }
        .section h2 {
            color: #2c3e50;
            margin-top: 0;
            border-bottom: 2px solid #3498db;
            padding-bottom: 10px;
        }
        .api-info {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 6px;
            margin-bottom: 20px;
        }
        .api-info h3 {
            margin-top: 0;
            color: #495057;
        }
        .method-tag {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
            color: white;
        }
        .method-post { background-color: #28a745; }
        .method-get { background-color: #007bff; }
        .endpoint {
            font-family: 'Courier New', monospace;
            background: #f1f3f4;
            padding: 8px 12px;
            border-radius: 4px;
            margin: 8px 0;
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #555;
        }
        input[type="text"], input[type="number"], select, textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            box-sizing: border-box;
        }
        textarea {
            height: 120px;
            resize: vertical;
        }
        .button-group {
            text-align: center;
            margin: 30px 0;
        }
        button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin: 0 10px;
        }
        button:hover {
            background-color: #0056b3;
        }
        button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        button.get-btn {
            background-color: #28a745;
        }
        button.post-btn {
            background-color: #dc3545;
        }
        .response {
            margin-top: 30px;
            padding: 20px;
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            display: none;
        }
        .response.show {
            display: block;
        }
        .response h3 {
            margin-top: 0;
            color: #333;
        }
        .status {
            padding: 5px 10px;
            border-radius: 4px;
            color: white;
            font-weight: bold;
        }
        .status.success {
            background-color: #28a745;
        }
        .status.error {
            background-color: #dc3545;
        }
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .download-info {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
            padding: 15px;
            border-radius: 4px;
            margin: 15px 0;
        }
        .code-block {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 15px;
            margin: 10px 0;
            font-family: 'Courier New', monospace;
            font-size: 14px;
            overflow-x: auto;
        }
        .param-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
        }
        .param-item {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 6px;
            border-left: 4px solid #28a745;
        }
        .param-item h4 {
            margin-top: 0;
            color: #155724;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>订单导出接口测试 (端口82)</h1>

        <div class="section">
            <h2>📋 接口信息</h2>

            <div class="api-info">
                <h3><span class="method-tag method-post">POST</span> /store/order/export</h3>
                <div class="endpoint">http://localhost:82/store/order/export</div>
                <p>订单数据导出接口，支持POST请求，请求体包含导出参数，返回Excel文件</p>
            </div>

            <div class="api-info">
                <h3><span class="method-tag method-get">GET</span> /store/order/exportGet</h3>
                <div class="endpoint">http://localhost:82/store/order/exportGet</div>
                <p>订单数据导出接口，支持GET请求，参数通过URL传递，返回Excel文件</p>
            </div>
        </div>

        <div class="section">
            <h2>⚙️ 测试参数配置</h2>

            <div class="form-group">
                <label for="orderType">订单类型 (orderType)：</label>
                <select id="orderType">
                    <option value="">全部订单</option>
                    <option value="1">待发货订单</option>
                    <option value="2">待审核订单</option>
                    <option value="3">待收货订单</option>
                    <option value="4">待付款订单</option>
                    <option value="5">已完成订单</option>
                    <option value="6">已取消订单</option>
                </select>
            </div>

            <div class="form-group">
                <label for="startTime">开始日期 (startTime)：</label>
                <input type="date" id="startTime" value="2025-08-31">
                <small style="color: #666;">LocalDate格式: yyyy-MM-dd</small>
            </div>

            <div class="form-group">
                <label for="endTime">结束日期 (endTime)：</label>
                <input type="date" id="endTime" value="2025-08-31">
                <small style="color: #666;">LocalDate格式: yyyy-MM-dd</small>
            </div>

            <div class="form-group">
                <label for="orderNo">订单号 (orderNo)：</label>
                <input type="text" id="orderNo" placeholder="输入订单号筛选">
            </div>

            <div class="form-group">
                <label for="buyerName">买家姓名 (buyerName)：</label>
                <input type="text" id="buyerName" placeholder="输入买家姓名筛选">
            </div>
        </div>

        <div class="section">
            <h2>🚀 模拟下载测试</h2>

            <div class="button-group">
                <button onclick="testGetDownload()" class="get-btn">🟢 GET下载测试</button>
                <button onclick="testPostDownload()" class="post-btn">🔴 POST下载测试</button>
                <button onclick="clearResponse()">清空结果</button>
            </div>

            <div id="response" class="response">
                <h3>测试结果</h3>
                <div id="responseContent"></div>
            </div>
        </div>

        <div class="section">
            <h2>📝 测试说明</h2>
            <div class="download-info">
                <strong>🎯 测试说明：</strong><br>
                • 使用端口 <strong>82</strong> 进行测试<br>
                • GET下载：参数通过URL传递<br>
                • POST下载：参数通过JSON请求体传递<br>
                • 时间参数：LocalDate格式 (yyyy-MM-dd)<br>
                • 成功时会自动触发文件下载<br>
                • 查看浏览器控制台获取详细调试信息
            </div>

            <h4>测试步骤：</h4>
            <ol>
                <li>确保Spring Boot应用已启动（端口82）</li>
                <li>配置筛选参数（可选）</li>
                <li>点击对应按钮进行测试</li>
                <li>查看测试结果和下载状态</li>
            </ol>

            <h4>预期结果：</h4>
            <ul>
                <li>✅ 成功时显示下载成功信息</li>
                <li>✅ 浏览器自动开始下载Excel文件</li>
                <li>✅ 显示详细的请求和响应信息</li>
                <li>❌ 失败时显示具体的错误信息和解决方案</li>
            </ul>
        </div>
    </div>

    <script>
        // 测试GET下载
        async function testGetDownload() {
            const responseDiv = document.getElementById('response');
            const responseContent = document.getElementById('responseContent');
            const testButton = event.target;

            // 禁用按钮并显示加载状态
            testButton.disabled = true;
            testButton.innerHTML = '<span class="loading"></span> GET下载测试中...';

            try {
                // 收集参数
                const params = {
                    orderType: document.getElementById('orderType').value,
                    startTime: document.getElementById('startTime').value,
                    endTime: document.getElementById('endTime').value,
                    orderNo: document.getElementById('orderNo').value,
                    buyerName: document.getElementById('buyerName').value
                };

                // 过滤空参数
                Object.keys(params).forEach(key => {
                    if (!params[key] || params[key] === '') {
                        delete params[key];
                    }
                });

                // GET请求
                const queryString = new URLSearchParams(params).toString();
                const url = 'http://localhost:82/store/order/exportGet' + (queryString ? '?' + queryString : '');
                const options = { method: 'GET' };

                console.log('🚀 发送GET导出请求:', { url, params });

                // 显示发送信息
                let result = '<div class="status success">📤 发送GET请求中...</div>';
                result += '<h4>请求信息：</h4>';
                result += '<div class="code-block">';
                result += `接口: GET ${url}<br>`;
                result += `参数: ${JSON.stringify(params, null, 2)}<br>`;
                result += `时间格式: LocalDate (yyyy-MM-dd)<br>`;
                result += '</div>';

                responseContent.innerHTML = result;
                responseDiv.classList.add('show');

                const response = await fetch(url, options);
                console.log('📥 收到GET响应:', response);

                await processDownloadResponse(response, result, 'GET');

            } catch (error) {
                console.error('❌ GET下载失败:', error);
                handleDownloadError(error, 'GET');
            } finally {
                // 恢复按钮状态
                testButton.disabled = false;
                testButton.innerHTML = '🟢 GET下载测试';
            }
        }

        // 测试POST下载
        async function testPostDownload() {
            const responseDiv = document.getElementById('response');
            const responseContent = document.getElementById('responseContent');
            const testButton = event.target;

            // 禁用按钮并显示加载状态
            testButton.disabled = true;
            testButton.innerHTML = '<span class="loading"></span> POST下载测试中...';

            try {
                // 收集参数
                const params = {
                    orderType: document.getElementById('orderType').value,
                    startTime: document.getElementById('startTime').value,
                    endTime: document.getElementById('endTime').value,
                    orderNo: document.getElementById('orderNo').value,
                    buyerName: document.getElementById('buyerName').value
                };

                // 过滤空参数
                Object.keys(params).forEach(key => {
                    if (!params[key] || params[key] === '') {
                        delete params[key];
                    }
                });

                // POST请求
                const url = 'http://localhost:82/store/order/export';
                const options = {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(params)
                };

                console.log('🚀 发送POST导出请求:', { url, params });

                // 显示发送信息
                let result = '<div class="status success">📤 发送POST请求中...</div>';
                result += '<h4>请求信息：</h4>';
                result += '<div class="code-block">';
                result += `接口: POST ${url}<br>`;
                result += `参数: ${JSON.stringify(params, null, 2)}<br>`;
                result += `请求体: ${JSON.stringify(params, null, 2)}<br>`;
                result += `时间格式: LocalDate (yyyy-MM-dd)<br>`;
                result += '</div>';

                responseContent.innerHTML = result;
                responseDiv.classList.add('show');

                const response = await fetch(url, options);
                console.log('📥 收到POST响应:', response);

                await processDownloadResponse(response, result, 'POST');

            } catch (error) {
                console.error('❌ POST下载失败:', error);
                handleDownloadError(error, 'POST');
            } finally {
                // 恢复按钮状态
                testButton.disabled = false;
                testButton.innerHTML = '🔴 POST下载测试';
            }
        }

        // 处理下载响应（公共函数）
        async function processDownloadResponse(response, result, method) {
            // 更新响应信息
            result += '<h4>📥 响应信息：</h4>';
            result += `<div class="status ${response.ok ? 'success' : 'error'}">`;
            result += `状态码: ${response.status} ${response.statusText}</div>`;

            // 显示响应头信息
            result += '<h4>响应头信息：</h4>';
            result += '<div class="code-block">';
            for (let [key, value] of response.headers.entries()) {
                result += `${key}: ${value}<br>`;
            }
            result += '</div>';

            if (response.ok) {
                // 检查是否是文件下载响应
                const contentType = response.headers.get('content-type');
                const contentDisposition = response.headers.get('content-disposition');

                if (contentDisposition && contentDisposition.includes('attachment')) {
                    // 🎉 是文件下载响应 - 模拟下载成功！
                    result += '<div class="download-info">';
                    result += `🎉 <strong>${method}模拟下载成功！</strong><br>`;
                    result += `📄 内容类型: ${contentType}<br>`;
                    result += `📁 文件信息: ${contentDisposition}<br>`;
                    result += '🔄 正在触发文件下载...<br>';
                    result += '✅ 请检查浏览器的下载文件夹';
                    result += '</div>';

                    // 处理文件下载
                    const blob = await response.blob();
                    const filename = extractFilename(contentDisposition) || `order-export-${method.toLowerCase()}.xlsx`;

                    console.log(`📁 开始${method}下载文件:`, filename);
                    downloadFile(blob, filename);

                    result += `<div class="download-info">`;
                    result += `✅ ${method}文件下载已完成！<br>`;
                    result += `📄 文件名: ${filename}<br>`;
                    result += `📊 文件大小: ${formatFileSize(blob.size)}<br>`;
                    result += `🔗 请求方式: ${method}`;
                    result += `</div>`;

                } else {
                    // 不是文件下载，显示响应内容
                    result += '<h4>📄 响应内容：</h4>';
                    const text = await response.text();
                    result += `<div class="code-block">${text}</div>`;

                    if (text.includes('导出订单数据失败') || text.includes('error')) {
                        result += '<div class="status error">⚠️ 服务器返回错误信息，可能需要检查后端实现</div>';
                    }
                }
            } else {
                // 请求失败
                const errorText = await response.text();
                result += '<h4>❌ 错误信息：</h4>';
                result += `<div class="code-block">${errorText}</div>`;

                result += `<div class="status error">❌ ${method}模拟下载失败</div>`;
            }

            // 更新显示内容
            document.getElementById('responseContent').innerHTML = result;
        }

        // 处理下载错误（公共函数）
        function handleDownloadError(error, method) {
            const responseDiv = document.getElementById('response');
            const responseContent = document.getElementById('responseContent');

            let errorMessage = `<div class="status error">❌ ${method}下载失败：${error.message}</div>`;
            errorMessage += '<br><br><strong>🔍 错误分析：</strong><br>';

            if (error.message.includes('Failed to fetch')) {
                errorMessage += '• 网络连接失败 - 请检查服务器是否启动 (端口82)<br>';
                errorMessage += '• CORS跨域限制 - 请检查服务器配置<br>';
                errorMessage += '• 接口地址错误 - 请确认URL是否正确<br>';
            } else if (error.message.includes('NetworkError')) {
                errorMessage += '• 网络错误 - 请检查网络连接<br>';
            } else if (error.message.includes('TypeError')) {
                errorMessage += '• 请求配置错误 - 请检查参数格式<br>';
            } else {
                errorMessage += '• 未知错误 - 请查看浏览器控制台详情<br>';
            }

            errorMessage += '<br><strong>💡 建议解决方案：</strong><br>';
            errorMessage += '1. 确认服务器已启动并可访问 (http://localhost:82)<br>';
            errorMessage += '2. 检查接口URL和参数是否正确<br>';
            errorMessage += '3. 查看浏览器控制台的详细错误信息<br>';
            errorMessage += `4. 确认${method}导出接口已正确实现<br>`;

            responseContent.innerHTML = errorMessage;
            responseDiv.classList.add('show');
        }

        // 从Content-Disposition提取文件名
        function extractFilename(contentDisposition) {
            if (!contentDisposition) return null;

            const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
            if (filenameMatch && filenameMatch[1]) {
                return filenameMatch[1].replace(/['"]/g, '');
            }
            return null;
        }

        // 下载文件
        function downloadFile(blob, filename) {
            try {
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = filename;
                a.style.display = 'none';

                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);

                // 清理URL对象
                setTimeout(() => {
                    window.URL.revokeObjectURL(url);
                }, 100);

                console.log('✅ 文件下载成功:', filename);
            } catch (error) {
                console.error('❌ 文件下载失败:', error);
                throw new Error('文件下载失败：' + error.message);
            }
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';

            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));

            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 清空响应
        function clearResponse() {
            const responseDiv = document.getElementById('response');
            const responseContent = document.getElementById('responseContent');
            responseContent.innerHTML = '';
            responseDiv.classList.remove('show');
        }

        // 页面加载时的初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('📋 订单导出模拟下载测试页面已加载 (端口82)');

            // 设置默认日期为今天
            const now = new Date();
            const today = now.toISOString().split('T')[0];
            document.getElementById('startTime').value = today;
            document.getElementById('endTime').value = today;
        });
    </script>
</body>
</html>
